<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class StoreCouponIssueUser extends Model
{
    use HasFactory;
    protected $table = 'store_coupon_issue_user';

    /**
     * szk
     * 用户领取优惠券
     * @param $uid
     * @param $couponId
     * @return mixed
     */
    public static function useradd($uid, $couponId)
    {
        $userAttached = self::where('uid', $uid)->where('issue_coupon_id', $couponId)->first();
        if ($userAttached) {
            throw new \ErrorException('已经领取过了');
        }
        $addTime = strtotime(date('Y-m-d H:i:s'));
        return self::insert(['uid' => $uid, 'issue_coupon_id' => $couponId, 'add_time' => $addTime]);
    }



    /**
     * szk
     * 查询个人优惠券
     * @param $id
     * @return array
     */
    public static function userStoreIssue($id)
    {
        return self::with('getDiscountData')->where('uid', $id)->get()->toArray();
    }

    /**
     * szk
     * 模型关联 个人优惠卷
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function getDiscountData()
    {
        return $this->belongsTo(StoreCoupon::class, 'issue_coupon_id', 'id');
    }
}
